package link.xieyu;

import cn.hutool.core.net.NetUtil;
import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.AddDomainRecordRequest;
import com.aliyun.alidns20150109.models.AddDomainRecordResponse;
import com.aliyun.alidns20150109.models.DeleteSubDomainRecordsRequest;
import com.aliyun.alidns20150109.models.UpdateDomainRecordRequest;
import com.aliyun.teaopenapi.models.Config;
import link.xieyu.config.ReadConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static link.xieyu.config.Constant.PROPERTIES_KEY;

/**
 * @author xieyu
 */
public class AnalysisRun {
    private final static Logger log = LoggerFactory.getLogger(AnalysisRun.class);
    static String recordId;
    /**
     * 最后一次解析ip
     */
    static String lastIp;

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        log.info("初始化client");
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "alidns.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.alidns20150109.Client(config);
    }


    public static void main(String[] args) throws Exception {
        Map<String, String> command = Arrays.stream(args)
                .filter(e -> e.contains("=")).map(e -> e.split("="))
                .collect(Collectors.toMap(e -> e[0], e -> e[1]));
        log.info("启动参数传入:{},读取配置文件:{}", command,
                 command.get(PROPERTIES_KEY) == null ? "aliyun.properties" : command.get(PROPERTIES_KEY));
        ReadConfig readConfig;
        if (command.get(PROPERTIES_KEY) == null) {
            readConfig = new ReadConfig();
        }
        else {
            readConfig = new ReadConfig(command.get(PROPERTIES_KEY));
        }
        Client client = createClient(readConfig.getAccess().getId(), readConfig.getAccess().getSecret());
        delAnalysis(readConfig, client);
        recordId = addAnalysis(readConfig, client);
        while (true) {
            log.info("开始修改dns云解析记录");
            TimeUnit.MINUTES.sleep(10);
            String currentIp = ipv6();
            if (Objects.equals(currentIp, lastIp)) {
                log.info("修改dns云解析记录,本次ipv6未改变,不进行处理");
                continue;
            }
            log.info("修改dns云解析记录,本次ipv6已改变,lastIP：{}，currentIp：{}", lastIp, currentIp);
            UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
            updateDomainRecordRequest.setRecordId(recordId);
            updateDomainRecordRequest.setRR(readConfig.getAliyunDomainAnalysis().getRr());
            updateDomainRecordRequest.setType(readConfig.getAliyunDomainAnalysis().getType());
            updateDomainRecordRequest.setValue(currentIp);
            client.updateDomainRecord(updateDomainRecordRequest);
        }
    }

    /**
     * 添加解析记录
     *
     * @param readConfig \
     * @param client     \
     * @return
     * @throws Exception \
     */
    private static String addAnalysis(ReadConfig readConfig, Client client) throws Exception {
        String ipv6 = ipv6();
        log.info("初始化添加dns云解析记录,ip:{}", ipv6);
        System.err.println("本机ip:" + ipv6);
        lastIp = ipv6;
        AddDomainRecordRequest addDomainRecordRequest = new AddDomainRecordRequest()
                .setLang("JAVA")
                .setDomainName(readConfig.getAliyunDomainAnalysis().getDomainName())
                .setType(readConfig.getAliyunDomainAnalysis().getType())
                .setValue(ipv6)
                .setRR(readConfig.getAliyunDomainAnalysis().getRr());
        // 复制代码运行请自行打印 API 的返回值
        AddDomainRecordResponse addDomainRecordResponse = client.addDomainRecord(addDomainRecordRequest);
        return addDomainRecordResponse.getBody().getRecordId();
    }

    private static String ipv6() {
        return NetUtil.localIpv6s()
                .stream()
                .filter(e -> e.startsWith("2409"))
                .map(e -> e.split("%")[0])
                .findAny().orElse("");
    }

    /**
     * 删除相关解析记录
     *
     * @param readConfig
     * @param client
     */
    private static void delAnalysis(ReadConfig readConfig, Client client) {
        log.info("初始化删除所有的dns云解析记录");
        DeleteSubDomainRecordsRequest deleteSubDomainRecordsRequest = new DeleteSubDomainRecordsRequest();
        deleteSubDomainRecordsRequest.setDomainName(readConfig.getAliyunDomainAnalysis().getDomainName());
        deleteSubDomainRecordsRequest.setRR(readConfig.getAliyunDomainAnalysis().getRr());
        try {
            client.deleteSubDomainRecords(deleteSubDomainRecordsRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("所有的dns云解析记录删除完成");
    }
}
